import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:uuid/uuid.dart';
import 'scan_result_service.dart';

class AIService {
  final String apiUrl = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
  final String apiKey = '566a49ec50d143ee93d94b4fc14ba57e.Mm0QTksfc0zAv4g3';
  final ScanResultService _scanResultService;
  final Uuid _uuid = Uuid();
  final Dio _dio = Dio();

  AIService(this._scanResultService) {
    // 配置dio
    _dio.options.headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $apiKey',
    };
    _dio.options.connectTimeout = const Duration(seconds: 30);
    _dio.options.receiveTimeout = const Duration(seconds: 30);
  }

  // 保存图片到本地
  Future<String> saveImageLocally(File imageFile) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final scanImagesDir = Directory('${directory.path}/scan_images');

      // 确保目录存在
      if (!await scanImagesDir.exists()) {
        await scanImagesDir.create(recursive: true);
      }

      final fileName = '${_uuid.v4()}${path.extension(imageFile.path)}';
      final savedImage = await imageFile.copy(
        '${scanImagesDir.path}/$fileName',
      );
      return savedImage.path;
    } catch (e) {
      print('保存图片错误: $e');
      // 如果失败，返回原始路径
      return imageFile.path;
    }
  }

  // 将图片转为base64编码
  Future<String> imageToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    return base64Encode(imageBytes);
  }

  // 发送图片和问题到AI API
  Future<Map<String, dynamic>> sendImageAndQuestion({
    required String userId,
    required File imageFile,
    required String question,
  }) async {
    try {
      // 保存图片到本地
      final localImagePath = await saveImageLocally(imageFile);

      // 将图片转为base64
      final base64Image = await imageToBase64(imageFile);

      // 构建请求数据
      final requestData = {
        'model': 'glm-4v-plus-0111',
        'messages': [
          {
            'role': 'user',
            'content': [
              {
                'type': 'image_url',
                'image_url': {'url': base64Image},
              },
              {'type': 'text', 'text': question},
            ],
          },
        ],
      };

      // 发送请求
      final response = await _dio.post(apiUrl, data: requestData);

      if (response.statusCode == 200) {
        final result = response.data;
        final aiResponse = result['choices'][0]['message']['content'];

        // 保存结果到ScanResultModel
        final scanResult = await _scanResultService.createScanResult(
          userId: userId,
          imageUrl: localImagePath,
          result: aiResponse,
          description: aiResponse, // 初始描述使用相同的回答
        );

        return {
          'success': true,
          'scanResult': scanResult,
          'response': aiResponse,
        };
      } else {
        return {
          'success': false,
          'error': 'API错误: ${response.statusCode}',
          'details': response.data,
        };
      }
    } on DioException catch (e) {
      return {
        'success': false,
        'error': '请求失败: ${e.type}',
        'details': e.message ?? 'Unknown error',
      };
    } catch (e) {
      return {'success': false, 'error': '请求失败', 'details': e.toString()};
    }
  }

  // 继续与AI对话
  Future<String?> continueConversation({
    required String question,
    required List<Map<String, String>> history,
  }) async {
    try {
      // 构建消息历史
      final messages =
          history
              .map((msg) => {'role': msg['role'], 'content': msg['content']})
              .toList();

      // 添加新问题
      messages.add({'role': 'user', 'content': question});

      // 构建请求数据
      final requestData = {'model': 'glm-4v-plus-0111', 'messages': messages};

      // 发送请求
      final response = await _dio.post(apiUrl, data: requestData);

      if (response.statusCode == 200) {
        final result = response.data;
        return result['choices'][0]['message']['content'];
      } else {
        print('请求失败: ${response.statusCode}');
        return null;
      }
    } on DioException catch (e) {
      print('Dio错误: ${e.type}, ${e.message}');
      return null;
    } catch (e) {
      print('未知错误: $e');
      return null;
    }
  }
}
